package controllers;

import static util.FindFoodUtil.empty;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import models.Category;
import models.Restaurant;
import models.ZipcodeGeo;
import play.Logger;
import play.Play;
import play.Play.Mode;
import play.cache.Cache;
import play.data.validation.Required;
import play.i18n.Messages;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.With;
import util.FindFoodUtil;
import util.IndexTank;
import util.GoogleGeocode.GeocodeException;

import com.flaptor.indextank.apiclient.IndexTankClient;
import com.flaptor.indextank.apiclient.IndexTankClient.Index;
import com.flaptor.indextank.apiclient.IndexTankClient.Query;
import com.flaptor.indextank.apiclient.IndexTankClient.SearchResults;
import com.javadocmd.simplelatlng.LatLng;

@With(Common.class)
public class Find extends Controller {

	public static void view() {
		// Load up a session-stored search if possible.
		if (renderArgs.get("restaurants") == null && session.contains("kw")
				&& !empty(session.get("kw"))) {
			String kw = session.get("kw");
			String cat = session.get("cat");
			String z = session.get("z");

			renderArgs.put("kwValue", kw);
			renderArgs.put("catValue", cat);
			renderArgs.put("zValue", z);

			ZipcodeGeo zipgeo = null;
			try {
				zipgeo = ZipcodeGeo.get(z);
			} catch (GeocodeException e) {
				// Leave zipgeo null.
			}
			Category category = Category.getByValue(cat);

			try {
				List<Restaurant> restaurants = IndexTank.performSearch(kw, zipgeo,
						category);
				renderArgs.put("restaurants", restaurants);
			} catch (Exception e) {
				Logger.error(e, "Problem completing search query.");
				flash.error(Messages.get("error.server"));
			}

			if (empty(renderArgs.get("restaurants", List.class)))
				renderArgs.put("noResults", Boolean.TRUE);
		}

		FindFoodUtil.loadCategories(renderArgs);
		render();
	}

	public static void doFind(
			@Required(message = "required.keywords") String kw, String cat,
			String z) {
		// Validate form fields.
		ZipcodeGeo zipgeo = null;
		if (!empty(z)) {
			try {
				zipgeo = ZipcodeGeo.get(z);
			} catch (GeocodeException e) {
				// Leave latLng null.
			}
			if (zipgeo == null)
				validation.addError("z", Messages.get("zipcode.invalid"));
		}

		if (validation.hasErrors()) {
			validation.keep();
			view();
		} else {
			// Save search parameters to session so that it can be rendered.
			session.put("kw", kw);
			session.put("cat", cat);
			session.put("z", z);
			view();
		}
	}

	public static void clear() {
		session.remove("kw");
		session.remove("cat");
		session.remove("z");
		view();
	}
}
